package www.wen.com.common.lib.util

import com.google.gson.Gson
import com.google.gson.JsonParser
import com.xuexiang.xupdate.entity.UpdateEntity
import com.xuexiang.xupdate.listener.IUpdateParseCallback
import com.xuexiang.xupdate.proxy.IUpdateParser
import www.wen.com.common.lib.data.entities.AppUpdateEntity

/**
 * @author WEN
 * @Description:
 * @date 2021/9/30 1:53
 */
class CustomUpdateParser : IUpdateParser {

    override fun parseJson(json: String?): UpdateEntity? = getParseResult(json)

    private fun getParseResult(json: String?): UpdateEntity? {
        if (json == null) return null
        if (!json.contains("code")) return null
        val code: Int = JsonParser().parse(json).asJsonObject.get("code").asInt
        return if (code == 0) {
            val data = JsonParser().parse(json).asJsonObject.getAsJsonObject("data")
            val appUpdateEntity = Gson().fromJson(data, AppUpdateEntity::class.java)
            UpdateEntity()
                    .setHasUpdate(appUpdateEntity.lastVersion.versionCode>LocalInfoUtil.getLocalVersionCode())
//                    .setHasUpdate(true)
                    .setForce(appUpdateEntity.forceFlag)
                    .setIsIgnorable(!appUpdateEntity.forceFlag)
                    .setVersionCode(LocalInfoUtil.getLocalVersionCode())
                    .setVersionName(LocalInfoUtil.getLocalVersionName())
                    .setUpdateContent(appUpdateEntity.lastVersion.versionNote)
                    .setDownloadUrl(appUpdateEntity.lastVersion.url)
                    .setSize(0)
        } else {
            null
        }
    }

    override fun parseJson(json: String?, callback: IUpdateParseCallback?) {}

    override fun isAsyncParser(): Boolean = false

}